package com.lm.liaoming.authority;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;

import java.util.ArrayList;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * 权限处理
 */
public class AuthorityManager {
    private Activity context;

    public AuthorityManager(Activity context) {
        this.context = context;
    }

    public interface OnAuthorityListener {
        void onAuthoritySuccess();
    }


    /*申请定位权限*/
    public AuthorityManager requestLocation() {
        ActivityCompat.requestPermissions(context,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                AuthorityType.LOCATION);
        return this;
    }

    /*申请相机权限*/
    public AuthorityManager requestCamera() {
        ActivityCompat.requestPermissions(context,
                new String[]{Manifest.permission.CAMERA},
                AuthorityType.CAMERA);
        return this;
    }

    /*申请录音权限*/
    public AuthorityManager requestRecord() {
        ActivityCompat.requestPermissions(context,
                new String[]{Manifest.permission.RECORD_AUDIO},
                AuthorityType.RECORD);
        return this;
    }

    /*申请存储权限*/
    public AuthorityManager requestStorage() {
        ActivityCompat.requestPermissions(context,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},
                AuthorityType.STORAGE);
        return this;
    }

    public void reqestAll(OnAuthorityListener onAuthorityListener) {
        List<String> mPermissionList = new ArrayList<>();
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE,
           };
        //逐个判断你要的权限是否已经通过
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(context, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);//添加还未授予的权限
            }
        }
        //申请权限
        if (mPermissionList.size() > 0) {//有权限没有通过，需要申请
            ActivityCompat.requestPermissions(context, permissions, AuthorityType.ALL);
        } else {
            //说明权限都已经通过，可以做你想做的事情去
            onAuthorityListener.onAuthoritySuccess();
        }
    }


}
